﻿#include"list.h"

// 新节点
static ListNode* BuyNode(LTDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("BuyNode.malloc");
		return NULL;
	}

	newnode->prev = newnode;
	newnode->data = x;
	newnode->next = newnode;

	return newnode;
}

// 初始化
ListNode* InitList()
{
	ListNode* phead = BuyNode(-1);

	phead->prev = phead;
	phead->next = phead;
	return phead;
}

// 打印
void PrintList(ListNode* phead)
{
	assert(phead);

	ListNode* cur = phead->next;

	printf("phead<-->");
	while (cur != phead)
	{
		printf("%d<-->", cur->data);
		cur = cur->next;
	}
	printf("phead\n");
}

// 尾插
void LTPushBack(ListNode* phead, LTDataType x)
{
	assert(phead);

	ListNode* newndoe = BuyNode(x);

	ListNode* tail = phead->prev;
	tail->next = newndoe;
	newndoe->prev = tail;
	newndoe->next = phead;
	phead->prev = newndoe;
}

// 尾删
void LTPopBack(ListNode* phead)
{
	assert(phead);
	if (phead->next == phead)
	{
		printf("链表为空\n");
		return;
	} 

	ListNode* tail = phead->prev;
	ListNode* tailprev = tail->prev;
	free(tail);
	phead->prev = tailprev;
	tailprev->next = phead;
}

// 头插
void LTPushFront(ListNode* phead, LTDataType x)
{
	assert(phead);

	ListNode* newndoe = BuyNode(x);

	ListNode* next = phead->next;
	phead->next = newndoe;
	newndoe->prev = phead;
	newndoe->next = next;
	next->prev = newndoe;
}

// 头删
void LTPopFront(ListNode* phead)
{
	assert(phead);
	if (phead->next == phead)
	{
		printf("链表为空\n");
		return;
	}

	ListNode* next = phead->next;
	ListNode* nextnext = next->next;
	free(next);
	phead->next = nextnext;
	nextnext->prev = phead;
}

// 查找
void LTFind(ListNode* phead, LTDataType x)
{
	assert(phead);

	ListNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
			return cur;

		cur = cur->next;
	}

	return NULL;
}

// 在pos节点之前插入
void LTInsert(ListNode* pos, LTDataType x)
{
	assert(pos);

	ListNode* newnode = BuyNode(x);

	ListNode* prev = pos->prev;
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}

// 删除pos节点
void LTErase(ListNode* pos)
{
	assert(pos);
	
	ListNode* prev = pos->prev;
	ListNode* next = pos->next;
	free(pos);
	prev->next = next;
	next->prev = prev;
}

// 释放链表
void LTDestroy(ListNode* phead)
{
	assert(phead);

	ListNode* cur = phead->next;
	while (cur != phead)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
}



